package com.freeman.cement.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.freeman.cement.entity.ResponseResult;
import com.freeman.cement.exception.AppException;
import com.freeman.cement.exception.AppExceptionCodeMsg;
import com.freeman.cement.mapper.MessageDao;
import com.freeman.cement.entity.Message;
import com.freeman.cement.service.MessageService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;

@Service
public class MessageServiceImpl implements MessageService {
    @Resource
    private MessageDao dao;

    @Override
    public ResponseResult selectMessage(int dutyRoomId, int pageNo, int pageSize) {
        PageHelper.startPage(pageNo, pageSize, true);
        List<Message> msgs = dao.selectMessagesByReceiver(dutyRoomId, null, null);
        PageInfo<Message> pageInfo = new PageInfo<Message>(msgs);
        msgs.forEach(s -> {
            if (StringUtils.isBlank(s.getSenderName())) {
                s.setSenderName("系统");
            }
            //这里有日期转换的问题，需要设成东八时区，但下面代码不能用
            /*if(s.getSendtime() != null){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
                String dateStr = sdf.format(s.getSendtime());
                try {
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    s.setSendtime(df.parse(dateStr));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }*/
        });
        return ResponseResult.success(pageInfo);

        /*PageHelper.startPage(pageNo, pageSize, true);
        List<Message> msgs = dao.selectMessagesByReceiver(receiver);
        PageInfo<Message> pageInfo = new PageInfo<Message>(msgs);
        List<JSONObject> list = new ArrayList<>();
        msgs.forEach(s -> {
            JSONObject item = new JSONObject();
            item.put("content", JSON.parseObject(s.getContent()));
            item.put("sendtime", s.getSendtime());
            item.put("readtimes", s.getReadtimes());
            String sendName = s.getSenderName();
            if (StringUtils.isBlank(sendName)) {
                sendName = "系统";
            }
            item.put("senderName", sendName);
            item.put("id", s.getId());
            list.add(item);
        });
        JSONObject object = new JSONObject();
        //数据总条数
        object.put("recordCount", pageInfo.getTotal());
        //数据总页数
        object.put("pageCount", pageInfo.getPages());
        object.put("pageNo", pageNo);
        object.put("pageSize", pageSize);
        object.put("list", list);
        return object;*/
    }

    private Date dateStringToDate(String time) {
        Date date = null;
        if (StringUtils.isNotBlank(time)) {
            try {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                date = simpleDateFormat.parse(time);
            } catch (Exception e) {
                throw new AppException(AppExceptionCodeMsg.TIME_STRING_FORMAT_IS_WRONG);
            }
        }
        return date;
    }

    @Override
    public ResponseResult selectUnreadMessage(int dutyRoomId, int count, String after) {
        Date _after = null;
        if(after != null && StringUtils.isNotBlank(after)){
            _after = dateStringToDate(after);
        }

        PageHelper.startPage(1, count, true);
        List<Message> msgs = dao.selectMessagesByReceiver(dutyRoomId, 0, _after);
        PageInfo<Message> pageInfo = new PageInfo<Message>(msgs);
        msgs.forEach(s -> {
            if (StringUtils.isBlank(s.getSenderName())) {
                s.setSenderName("系统");
            }
            //这里有日期转换的问题，需要设成东八时区，但下面代码不能用
            /*if(s.getSendtime() != null){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
                String dateStr = sdf.format(s.getSendtime());
                try {
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    s.setSendtime(df.parse(dateStr));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }*/
        });
        return ResponseResult.success(pageInfo);
    }

    @Override
    public ResponseResult readTimesAddOne(int id) {
        if (id > 0) {
            if (dao.readTimesAddOne(id) > 0) {
                QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
                queryWrapper.select("readtimes");
                queryWrapper.eq("id", id);
                List<Map<String, Object>> maps = dao.selectMaps(queryWrapper);
                if (maps != null && maps.size() > 0 && maps.get(0).containsKey("readtimes")) {
                    return ResponseResult.successMsg("已阅读" + maps.get(0).get("readtimes") + "次");
                }
                return ResponseResult.successMsg("已阅读");
            } else {
                return ResponseResult.error(50007, "阅读次数未记录");
            }
        } else {
            throw new AppException(AppExceptionCodeMsg.ID_IS_NULL);
        }
    }

}
